<?php

namespace app\beautiful\controller\miniapp\member\goods;

use app\BaseController;

use app\beautiful\logic\order\OrderLogic;

use app\beautiful\model\mall\GoodsCategoryModel;

use app\beautiful\model\mall\GoodsModel;

use app\beautiful\model\mall\GoodsSkuModel;

use app\beautiful\model\logs\GoodsViewsModel;

use app\beautiful\model\member\MemberModel;
use think\facade\Db;



class Goods extends BaseController{

    

  

    

    

    

    

    public function getGoodsCategory()

    {

        $return = $this->getCategoryData(0);

        return $this->success($return);

    }



    protected function getCategoryData($pid=0)

    {

        $category= GoodsCategoryModel::where([

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['pid','=',$pid]

        ])->order(['sort'=>'desc','add_time'=>'desc'])

            ->field('category_id,name,icon')

            ->select()->toArray();

        if(!empty($category)){

            foreach ($category as $k => $v){

                $category[$k]['children']= $this->getCategoryData($v['category_id']);

            }

        }

        return $category;

    }

    

    public function getGoodsDetail(){

         $goods_id = $this->request->param('goods_id/d',0);



        if(null === $goods = GoodsModel::find($goods_id)) return $this->error('商品不存在');

        if($goods->shop_id != $this->request->shopId) return $this->error('商品不存在');

        if($goods->is_delete == 1) return $this->error('商品不存在');

        if($goods->is_open_yu != 0) return $this->error('该商品为预售商品');

        if($goods->status != 1) return $this->error('商品已下架');



        $sku=GoodsSkuModel::where([['goods_id','=',$goods_id],['is_delete','=',0]])

                ->field('sku_id,name,original_price,vip_price,quota')

                ->select()->toArray() ?? [];



        $detail=[

            'goods_id'=>$goods_id,

            'name'=>$goods->name,

            'original_price'=>$goods->original_price,

            'quota'=>$goods->quota,

            'fictitious_take_count'=>$goods->fictitious_take_count,

            'vip_price'=>$goods->vip_price,

            'is_have_sku'=>$goods->is_have_sku,

            'rotation'=>$goods->rotation,

            'goods_details'=>$goods->goods_details,

            'purchase_information' => $goods->purchase_information,

            'cover_img' => $goods->cover_img,

            'sku'=>$sku,

        ];

        //记录产品的访问记录

        $GoodsViewsModel = new GoodsViewsModel();

        $GoodsViewsModel->save([

            'shop_id'   => $this->request->shopId,

            'goods_id'  => $goods_id

        ]);

        return $this->success(['detail'=>$detail]);



    }

    

    

    

    //根据产品的ID 下发产品并以SKU 为单位

    public function getGoodsListByGoodsIds(){

        $goodsIds = $this->request->param('goods_ids/a');

        if(empty($goodsIds)){

            return $this->error('请选择要查询的产品');

        }

        foreach($goodsIds as $k=>$v){

            $goodsIds[$k] = (int)$v;

        }

        $where = [

            ['shop_id','=', $this->request->shopId],

            ['goods_id','IN', $goodsIds],

            ['is_delete','=',0],

            ['status','=',1],

        ];

        $goods = GoodsModel::with(['sku'])->where($where)

            ->field('goods_id,cover_img,name,original_price,vip_price,quota,take_count,fictitious_take_count,type,discount_detail,vip_discount_type')

            ->json(['discount_detail'],true)

            ->select()

            ->toArray();

        

        $returnGoods = [];


        foreach($goods as $val){

            $item = $val;

            if(empty($val['sku'])){

                $item['sku'] = null;

                $returnGoods[] = $item;

            }else{

                foreach($val['sku'] as $sku){

                    $item['sku'] = $sku;

                    $returnGoods[] = $item;

                }

            }

        }

        return $this->success([

            'goods' => $returnGoods,

        ]);

    }

    

    

    public function getGoodsList()

    {

        $category_id=$this->request->param('category_id/d',0);

        $keyword=$this->request->param('keyword');

        $order_type=$this->request->param('order_type/d',1);



        $where=[

            ['shop_id','=',$this->request->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['is_open_yu','=',0],

        ];

        $return = [];

        if(!in_array($order_type,[1,2,3])) $order_type=1;

        if(!empty($category_id)){ //判断是否是父级ID 

            $category = GoodsCategoryModel::find($category_id);

            if(null !== $category){

                if($category->pid == 0){

                    $categorys = GoodsCategoryModel::where([

                        ['shop_id','=', $this->request->shopId],

                        ['pid','=', $category_id]

                    ])->column('category_id');

                    if(!empty($categorys)){

                        $categorys[] = $category_id;

                        $where[]=['category_id','IN',$categorys];

                    }else{

                        $where[]=['category_id','=',$category_id];

                    }

                }else{

                    $where[]=['category_id','=',$category_id];

                }

                $return['category'] = [

                    'category_id' => $category_id,

                    'name'        => $category->name,

                ];

            }

        }

        if(!empty($keyword)) $where[]=['name|code|purchase_information','like','%'.$keyword.'%'];



        if($order_type==1) $order=['sort'=>'desc','fictitious_take_count'=>'desc','vip_price'=>'desc'];

        if($order_type==2) $order=['fictitious_take_count'=>'desc','sort'=>'desc','vip_price'=>'desc'];

        if($order_type==3) $order=['vip_price'=>'desc','sort'=>'desc','fictitious_take_count'=>'desc'];



        $datas=GoodsModel::where($where)

            ->order($order)

            ->field('goods_id,cover_img,name,original_price,vip_price,quota,take_count,fictitious_take_count')

            ->limit($this->request->limit)

            ->page($this->request->page)

            ->select()

            ->toArray();

        $return['datas']=$datas;



        return $this->success($return);



    }



    public function getAllGoodsList()

    {

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['is_open_yu','=',0],

            ['quota','>',0],

        ];

        $order=['sort'=>'desc','fictitious_take_count'=>'desc','vip_price'=>'desc'];

        $datas= GoodsModel::with(['sku'=>function($query){

            $query->where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['quota','>',0],

                ['is_delete','=',0]

            ]);

        }])->where($where)

            ->order($order)

            ->field('goods_id,cover_img,name,original_price,vip_price,quota,take_count,fictitious_take_count,category_id')

            ->limit(500)

            ->select()

            ->toArray();

        $return['datas']=$datas;



        return $this->success($return);

    }



    public function createOrder()

    {

        $logistics_type=$this->request->param('logistics_type/d');

        $receiving_name=$this->request->param('receiving_name');

        $receiving_mobile=$this->request->param('receiving_mobile');

        $receiving_address_province=$this->request->param('receiving_address_province');

        $receiving_address_city=$this->request->param('receiving_address_city');

        $receiving_address_county=$this->request->param('receiving_address_county');

        $receiving_address_info=$this->request->param('receiving_address_info');

        $total_price = $this->request->param('total_price/f',0);

        $use_integral = $this->request->param('use_integral/d',0);

        $coupon_id = $this->request->param('coupon_id/d',0);

        $order_send_time = $this->request->param('order_send_time');

        $goods=$this->request->param('goods/a',[]);

        $type = $this->request->param('type/d',2);

        $from_type = $this->request->param('from_type/d',1);

        $params=[

            'member_id'=>$this->request->memberId,

            'logistics_type'=>$logistics_type,

            'receiving_name'=>$receiving_name,

            'receiving_mobile'=>$receiving_mobile,

            'receiving_address_province'=>$receiving_address_province,

            'receiving_address_city'=>$receiving_address_city,

            'receiving_address_county'=>$receiving_address_county,

            'receiving_address_info'=>$receiving_address_info,

            'total_price'=>$total_price,

            'use_integral'=>$use_integral,

            'coupon_id'=>$coupon_id,

            'order_send_time'=>$order_send_time,

            'goods'=>$goods,

            'from_type'=>$from_type

        ];

        Db::startTrans();

        try{

            $order_logic = OrderLogic::init($this->request->shopId);

            $order_id=$order_logic['normal']->createOrder($params);

//            if($type==3){
//                $order_id=$order_logic['set_meal']->createOrder($params);
//            }else{
//
//            }


            Db::commit();

            return $this->success(['order_id'=>$order_id]);

        } catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }



    }

    //测试
    //根据产品的ID 下发产品并以SKU 为单位
    public function getGoodsListByGoodsIdsTest(){

        $goodsIds = $this->request->param('goods_ids/a');

        if(empty($goodsIds)){

            return $this->error('请选择要查询的产品');

        }

        foreach($goodsIds as $k=>$v){

            $goodsIds[$k] = (int)$v;

        }


        $where = [

            ['shop_id','=', $this->request->shopId],

            ['goods_id','IN', $goodsIds],

            ['is_delete','=',0],

            ['status','=',1],

        ];

        $goods = GoodsModel::with(['sku'=>function($query){

            $query->json(['discount_detail'],true);

        }])->where($where)

            ->field('goods_id,cover_img,name,original_price,vip_price,quota,take_count,fictitious_take_count,vip_discount_type,discount_detail,type,send_type')

            ->json(['discount_detail'],true)

            ->select()

            ->toArray();


        $returnGoods = [];

        $member = MemberModel::find($this->request->memberId);
        $is_have_setMeal = 0;
        foreach($goods as $k=>$val){
            $val['send_type'] = explode(',',$val['send_type']);
            $val['vip_price'] = $val['original_price'];
            //当前用户价格
            $return = getPrice($val,$member,0);
            $val['vip_price'] = $return['price'];
            $val['vip_discount_price'] = $return['vip_discount_price'];
//            if($val['discount_detail']){
//
//                for ($i=0;$i<count($val['discount_detail']);$i++){
//
//                    if($val['discount_detail'][$i]['level_id']==$member->level_id){
//                        if($val['vip_discount_type']==1){
//                            $val['vip_price'] = $val['original_price']*($val['discount_detail'][$i]['member_price']/10);
//                        }
//                        if($val['vip_discount_type']==2){
//                            $val['vip_price'] = $val['discount_detail'][$i]['bid_price'];
//                        }
//                        if($val['vip_discount_type']==3){
//                            $val['vip_price'] = $val['original_price']-$val['discount_detail'][$i]['reduce_price'];
//                        }
//                    }
//                }
//            }
            if($val['type']==3) $is_have_setMeal = 1;

            $item = $val;

            if(empty($val['sku'])){

                $item['sku'] = null;

                $returnGoods[] = $item;

            }else{
                //当前用户价格
                if($val['sku']){
                    $sku = $this->skuMemberPrice($val['vip_discount_type'],$val['sku']);
                    $val['sku'] = $sku;
                }

                foreach($val['sku'] as $sku){

                    $item['sku'] = $sku;

                    $returnGoods[] = $item;

                }

            }




        }

        return $this->success([

            'goods' => $returnGoods,
            'is_have_setMeal'=>$is_have_setMeal

        ]);

    }
    /*sku中的当前用户价格*/
    protected function skuMemberPrice($vip_discount_type,$sku){
        $member = MemberModel::find($this->request->memberId);

        foreach ($sku as $kk=>$vv){

            $discount_detail = $vv['discount_detail'];
            $sku[$kk]['vip_price'] = $vv['original_price'];
            if($discount_detail){
                for ($i=0;$i<count($discount_detail);$i++){

                    if($discount_detail[$i]['level_id']==$member->level_id){
                        if($vip_discount_type==1){
                            $sku[$kk]['vip_price'] =$vv['original_price']*($discount_detail[$i]['member_price']/10);
                        }
                        if($vip_discount_type==2){
                            $sku[$kk]['vip_price'] = $discount_detail[$i]['bid_price'];
                        }
                        if($vip_discount_type==3){
                            $sku[$kk]['vip_price'] = $vv['original_price']-$discount_detail[$i]['reduce_price'];
                        }
                    }
                }
                if(isset($sku[$kk]['unit'])){
                    $sku[$kk]['unit'] = $sku[$kk]['unit']['group_detail_name'];
                }

                unset($sku[$kk]['discount_detail']);
            }

        }
        return $sku;
    }



}

